//////////////////////////////////////////////////////////////////////////
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include "Scenes/MainMenu.h"
#include "Application/Application.h"
#include <hge.h>
#include "Texture/Texture.h"
#include "TextureManager/TextureManager.h"
#include "Sprite/Sprite.h"
#include <cassert>
//////////////////////////////////////////////////////////////////////////
#define WINDOW_WIDTH  1024
#define WINDOW_HEIGHT 768
//////////////////////////////////////////////////////////////////////////
HGE*			hge			 = NULL;
Application*	application = NULL;
//////////////////////////////////////////////////////////////////////////
Sprite*		mouseSprite  = NULL;	
//////////////////////////////////////////////////////////////////////////
bool FrameFunc()
{
	assert(application);
	if(application)
	{
		application->update(hge->Timer_GetDelta());
		return application->exitReady();
	}

	return false;
}
//////////////////////////////////////////////////////////////////////////
bool RenderFunc()
{
	hge->Gfx_BeginScene();
	hge->Gfx_Clear(0);
	
	assert(application);
	if(application)
	{
		application->render();
	}

	if(mouseSprite)
	{
		float x;
		float y;
		hge->Input_GetMousePos(&x, &y);
		mouseSprite->setX(x);
		mouseSprite->setY(y);
		mouseSprite->render();
	}

	hge->Gfx_EndScene();

	return false;
}
//////////////////////////////////////////////////////////////////////////
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR cmdLine, int)
{
	_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );

	std::string commandLine = cmdLine;
	bool novsync = commandLine.find("-novsync") != commandLine.npos;

	hge = hgeCreate(HGE_VERSION);
	hge->System_SetState(HGE_FRAMEFUNC, FrameFunc);
	hge->System_SetState(HGE_RENDERFUNC, RenderFunc);
	hge->System_SetState(HGE_TITLE, L"bcity");
	hge->System_SetState(HGE_WINDOWED, true);
	hge->System_SetState(HGE_SCREENWIDTH, WINDOW_WIDTH);
	hge->System_SetState(HGE_SCREENHEIGHT, WINDOW_HEIGHT);
	hge->System_SetState(HGE_USESOUND, false);
	hge->System_SetState(HGE_SHOWSPLASH, false);
	if(!novsync)
		hge->System_SetState(HGE_FPS, HGEFPS_VSYNC);

	if(hge->System_Initiate())
	{
		Application::createApplication();
		application = Application::instance();

		Scene* scene = new MainMenu();
		application->loadScene(scene);

		mouseSprite = new Sprite();
		mouseSprite->setTexturePath(L"content/cursor.png");

		hge->System_Start();
		
		delete mouseSprite;
		mouseSprite = NULL;

		Application::deleteApplication();
	}
	else
	{
		MessageBox(NULL, hge->System_GetErrorMessage(), L"Error", MB_OK | MB_ICONERROR | MB_APPLMODAL);
	}

	hge->System_Shutdown();
	hge->Release();
	hge = NULL;
	
	return 0;
}